// 商品选择弹出框
var form, laytpl, element,table;
var goodsSelect = {
	selectList: [], // 选中商品所有数据res
	mode: 'spu', // 商品模式，spu：商品，sku：商品项
	maxNum: 0, // 最大商品数量
	minNum: 0, // 最小商品数量
	disabled: 0, // 不可选中
	cols: [], // 列名数据源
	filterData: {promotion_type: '', label_id: '', goods_name: ''}, //筛选数据
	goodsIdArr: [],
	skuIdAll: []
};

Array.prototype.indexOf = function (val) {
	for (var i = 0; i < this.length; i++) {
		if (this[i].goods_id && !this[i].sku_id) {
			if (this[i].goods_id == parseInt(val)) return i;
		} else if (this[i].sku_id) {
			if (this[i].sku_id == parseInt(val)) return i;
		} else {
			if (this[i] == val) return i;
		}

	}
	return -1;
};

Array.prototype.remove = function (val) {
	var index = this.indexOf(val);
	if (index > -1) {
		this.splice(index, 1);
	}
};

$(function () {

	$('.select-goods input[type="hidden"]').each(function () {
		goodsSelect[$(this).attr('name')] = $(this).val();
	});

	// 已选中的商品id
	var selectId = localStorage.getItem('goods_select_id') ? localStorage.getItem('goods_select_id').split(',') : [];
	$.ajax({
		url: ns.url("shop/goods/checkgoods"),
		data: {goods_ids: selectId.toString(), mode: goodsSelect.mode},
		dataType: 'JSON',
		type: 'POST',
		async: false,
		success: function (data) {
			if (!data) return;
			if (goodsSelect.mode == 'spu') {
				goodsSelect.goodsIdArr = data.split(',');
			} else {
				goodsSelect.skuIdAll = data.split(',');
			}
			dealWithTableSelectedNum();
		}
	});

	setCols();

	layui.use(['form', 'laytpl', 'element'], function () {
		form = layui.form, laytpl = layui.laytpl, element = layui.element;
		table = new Table({
			elem: '#goods_list',
			url: ns.url('shop/goods/goodsselect'),
			where: {
				is_virtual: goodsSelect.is_virtual,
				promotion: goodsSelect.promotion,
				goods_class: goodsSelect.goods_type,
				is_weigh: goodsSelect.is_weigh
			},
			cols: goodsSelect.cols,
			callback: function (res) {

				if (goodsSelect.mode == "sku") {
					//存储这sku的具体id
					$("input[name='goods_checkbox'][data-goods-id]").each(function () {
						var goods_id = $(this).attr("data-goods-id");
						var tr = $(this).parent().parent().parent();
						var data = getGoodsSkuData(goods_id);
						laytpl(data.sku_list).render(data, function (html) {
							tr.after(html);
							form.render();
							layer.photos({
								photos: '.img-wrap',
								anim: 5
							});
						});
					});
				}

				// 更新商品复选框状态
				if (goodsSelect.mode == 'spu') {
					for (var i = 0; i < goodsSelect.goodsIdArr.length; i++) {
						var goods = $("input[name='goods_checkbox'][data-goods-id='" + goodsSelect.goodsIdArr[i] + "']");
						if (goods.length) {
							goods.prop("checked", true);
							if (goodsSelect.disabled == 1) {
								goods.attr("disabled", "disabled");
							}

							var json = JSON.parse($("input[name='goods_json'][data-goods-id=" + goodsSelect.goodsIdArr[i] + "]").val());
							var skuList = $("input[name='goods_sku_list_json'][data-goods-id=" + goodsSelect.goodsIdArr[i] + "]").val();
							json.selected_sku_list = skuList ? JSON.parse(skuList) : [];
							goodsSelect.selectList.push(json);

						}
					}
				} else if (goodsSelect.mode == 'sku') {
					for (var i = 0; i < goodsSelect.skuIdAll.length; i++) {
						var selected_goods_sku = $("input[name='goods_sku_checkbox'][data-sku-id='" + goodsSelect.skuIdAll[i] + "']");
						selected_goods_sku.prop("checked", true);
						if (selected_goods_sku.length) {
							var goods = $("input[name='goods_checkbox'][data-goods-id='" + selected_goods_sku.attr("data-goods-id") + "']");
							goods.prop("checked", true);
							if (goodsSelect.disabled == 1) {
								goods.attr("disabled", "disabled");
							}
						}
					}

				}

				form.render();
				initData();
				dealWithTableSelectedNum();

			}
		});

		//修改一级分类箭头切换
		element.on('collapse(oneCategory)', function (data) {
			$(".layui-colla-title").removeClass("active");
			if (data.show) {
				$(data.title).addClass("active");
			}
		});

		//修改二级分类箭头切换
		element.on('collapse(twoCategory)', function (data) {
			$(".select-goods-classification .select-goods-classification .layui-colla-title").removeClass("active");
			if (data.show) {
				$(data.title).addClass("active");
			}
		});

		//搜索商品名称或编码
		form.on('submit(search)', function (data) {
			formSearch();
		});

		//搜索类型切换
		form.on('select(select_type)', function (data) {
			formSearch();
		});

		//商品标签筛选
		form.on('select(label_id)', function (data) {
			formSearch();
		});

		//商品类型筛选
		form.on('select(goods_class)', function (data) {
			formSearch();
		});

		// 勾选商品
		form.on('checkbox(goods_checkbox_all)', function (data) {
			var all_checked = data.elem.checked;
			$("input[name='goods_checkbox']").each(function () {
				var checked = $(this).prop('checked');
				if (all_checked != checked) {
					$(this).next().click();
				}
			});
			dealWithTableSelectedNum();
		});

		// 勾选商品
		form.on('checkbox(goods_checkbox)', function (data) {
			var goods_id = $(data.elem).attr("data-goods-id"),
				json = {};

			$("input[name='goods_sku_checkbox'][data-goods-id='" + goods_id + "']").prop("checked", data.elem.checked);
			form.render();

			var spuLen = $("input[name='goods_checkbox'][data-goods-id=" + goods_id + "]:checked").length;
			if (spuLen) {
				json = JSON.parse($("input[name='goods_json'][data-goods-id=" + goods_id + "]").val());
				var skuList = $("input[name='goods_sku_list_json'][data-goods-id=" + goods_id + "]").val();
				json.selected_sku_list = skuList ? JSON.parse(skuList) : [];

				delete json.LAY_INDEX;
				delete json.LAY_TABLE_INDEX;

				goodsSelect.selectList.push(json);
				goodsSelect.goodsIdArr.push(goods_id);

			} else {

				for (var i = 0; i < goodsSelect.selectList.length; i++) {
					if (goodsSelect.selectList[i].goods_id == goods_id) {
						goodsSelect.selectList.splice(i, 1);
						break;
					}
				}
				goodsSelect.goodsIdArr.remove(goods_id);
			}
			$.unique(goodsSelect.goodsIdArr);

			var skuLen = $("input[name='goods_sku_checkbox'][data-goods-id=" + goods_id + "]")
			if (!skuLen.length) {
				goodsSelect.skuIdAll = [];
			}
			for (var i = 0; i < skuLen.length; i++) {
				var skuId = skuLen.eq(i).attr("data-sku-id");
				if (spuLen)
					goodsSelect.skuIdAll.push(skuId);
				else {
					goodsSelect.skuIdAll.remove(skuId);
				}
			}
			dealWithTableSelectedNum();
		});

		// 勾选商品SKU
		form.on('checkbox(goods_sku_checkbox)', function (data) {

			var goods_id = $(data.elem).attr("data-goods-id"),
				sku_id = $(data.elem).attr("data-sku-id"),
				json = {};

			if ($("input[name='goods_sku_checkbox'][data-goods-id='" + goods_id + "']:checked").length) {
				var skuNoSelect = $("input[name='goods_sku_checkbox'][data-goods-id='" + goods_id + "']:checked").length - 1;
				var skuSelect = $("input[name='goods_sku_checkbox'][data-goods-id='" + goods_id + "']").length;

				if (skuNoSelect < skuSelect) {
					goodsSelect.goodsIdArr.push(goods_id);

					json = JSON.parse($("input[name='goods_json'][data-goods-id=" + goods_id + "]").val());
					delete json.LAY_INDEX;
					delete json.LAY_TABLE_INDEX;

					json.selected_sku_list = [];
					goodsSelect.selectList.push(json);
				}

				$("input[name='goods_checkbox'][data-goods-id='" + goods_id + "']").prop("checked", true);
			} else {

				$("input[name='goods_checkbox'][data-goods-id='" + goods_id + "']").prop("checked", false);
				goodsSelect.goodsIdArr.remove(goods_id);
				goodsSelect.selectList.remove(goods_id);
			}

			if (!goodsSelect.selectList.length) {
				goodsSelect.skuIdAll = [];
			}

			for (var i = 0; i < goodsSelect.selectList.length; i++) {
				if (goodsSelect.selectList[i].goods_id == goods_id) {
					// var skuLen = $("input[name='goods_sku_checkbox'][data-sku-id="+ sku_id +"]:checked").length;
					if (data.elem.checked) {
						goodsSelect.skuIdAll.push(sku_id);
						var skuVal = $("input[name='goods_sku_json'][data-sku-id=" + sku_id + "]").val()
						goodsSelect.selectList[i].selected_sku_list.push(JSON.parse(skuVal));
					} else {
						goodsSelect.skuIdAll.remove(sku_id);
						goodsSelect.selectList[i].selected_sku_list.remove(sku_id);
					}
					break;
				}
			}
			form.render();
		});

		$(".select-goods .select-goods-left dd").hover(function () {
			$(this).addClass("active");
		}, function () {
			$(this).removeClass("active");
		});

		$("body").on("click", ".select-goods-left .marketing-campaign dd", function () {
			$(this).addClass("text-color").siblings().removeClass("text-color");
			goodsSelect.filterData.promotion_type = $(this).attr("data-type");
			table.reload({
				page: {
					curr: 1
				},
				where: goodsSelect.filterData
			});
		});

		$("body").on("click", ".select-goods-left .commodity-group dd", function () {
			$(this).addClass("text-color").siblings().removeClass("text-color");
			goodsSelect.filterData.label_id = $(this).attr("data-group-id");
			table.reload({
				page: {
					curr: 1
				},
				where: goodsSelect.filterData
			});
		});

		$("body").on("click", ".select-goods-left dl", function () {
			if ($(this).hasClass("fold")) {
				$(this).removeClass("fold");
			} else {
				$(this).addClass("fold");
			}
		});

		$("body").on("click", ".select-goods-left dd", function (event) {
			$(this).parents("dl").removeClass("fold");
			$(this).parents("dl").siblings().addClass("fold");
			event.stopPropagation();
		});

		//分类切换
		$("body").on("click", ".classification-item", function (event) {
			var categoryId = $(this).attr("data-category_id");
			$(".classification-item").removeClass("text-color border-after-color");
			$(this).addClass("text-color border-after-color");
			$("input[name='category_id']").val(categoryId);
			formSearch();
			event.stopPropagation();
		});

		//商品信息展开
		$("body").on("click", ".contraction", function () {
			var goods_id = $(this).attr("data-goods-id");
			var open = $(this).attr("data-open");
			if (open == 1) {
				$(this).children("span").text("+");
				$(".js-sku-list-" + goods_id).hide();
			} else {
				$(this).children("span").text("-");
				$(".js-sku-list-" + goods_id).show();
			}
			$(this).attr("data-open", (open == 0 ? 1 : 0));
		});

	});

});

// 设置列名
function setCols() {
	switch (goodsSelect.promotion) {
		case '':
		case 'all':
		case 'module':
		case 'fenxiao':
		case 'bargain':
			goodsSelect.cols = [
				[
					{
						title: '<input type="checkbox" name="goods_checkbox_all" lay-skin="primary" lay-filter="goods_checkbox_all">',
						unresize: 'false',
						width: '8%',
						templet: '#checkbox',
					},
					{
						title: '商品',
						unresize: 'false',
						width: '62%',
						templet: '#goods_info'
					},
					{
						field: 'goods_stock',
						title: '库存',
						unresize: 'false',
						width: '15%'
					},
					{
						field: 'goods_class_name',
						title: '商品类型',
						unresize: 'false',
						width: '15%'
					}
				]
			];
			break;
		case 'pintuan':
			goodsSelect.cols = [
				[{
					title: '<input type="checkbox" name="goods_checkbox_all" lay-skin="primary" lay-filter="goods_checkbox_all">',
					unresize: 'false',
					width: '8%',
					templet: '#checkbox'
				}, {
					field: 'pintuan_name',
					title: '拼团活动',
					unresize: 'false',
					width: '20%',
				}, {
					title: '拼团商品',
					unresize: 'false',
					width: '33%',
					templet: '#goods_info'
				}, {
					field: 'pintuan_num',
					title: '参团人数',
					unresize: 'false',
					width: '13%'
				}, {
					field: 'group_num',
					title: '开团团队',
					unresize: 'false',
					width: '13%'
				}, {
					field: 'order_num',
					title: '购买人数',
					unresize: 'false',
					width: '13%'
				}]
			];
			break;
		case 'groupbuy':
			goodsSelect.cols = [
				[{
					title: '<input type="checkbox" name="goods_checkbox_all" lay-skin="primary" lay-filter="goods_checkbox_all">',
					unresize: 'false',
					width: '8%',
					templet: '#checkbox'
				}, {
					title: '团购商品',
					unresize: 'false',
					width: '47%',
					templet: '#goods_info'
				}, {
					field: 'price',
					title: '商品原价',
					unresize: 'false',
					width: '15%',
					templet: function (data) {
						return '￥' + data.price;
					}
				}, {
					field: 'groupbuy_price',
					title: '团购价格',
					unresize: 'false',
					width: '15%',
					templet: function (data) {
						return '￥' + data.groupbuy_price;
					}
				}, {
					field: 'buy_num',
					title: '起购量',
					unresize: 'false',
					width: '15%'
				}]
			];
			break;
		case 'presale':
			goodsSelect.cols = [
				[{
					title: '<input type="checkbox" name="goods_checkbox_all" lay-skin="primary" lay-filter="goods_checkbox_all">',
					unresize: 'false',
					width: '8%',
					templet: '#checkbox'
				}, {
					field: 'presale_name',
					title: '活动名称',
					unresize: 'false',
					width: '20%',
				}, {
					title: '预售商品',
					unresize: 'false',
					width: '50%',
					templet: '#goods_info'
				}, {
					field: 'presale_stock',
					title: '库存',
					unresize: 'false',
					width: '13%'
				}]
			];
			break;
		case 'pinfan':
			goodsSelect.cols = [
				[{
					title: '<input type="checkbox" name="goods_checkbox_all" lay-skin="primary" lay-filter="goods_checkbox_all">',
					unresize: 'false',
					width: '8%',
					templet: '#checkbox'
				}, {
					field: 'pintuan_name',
					title: '拼团返利',
					unresize: 'false',
					width: '20%',
				}, {
					title: '拼团商品',
					unresize: 'false',
					width: '33%',
					templet: '#goods_info'
				}, {
					field: 'pintuan_num',
					title: '参团人数',
					unresize: 'false',
					width: '13%'
				}, {
					field: 'group_num',
					title: '开团团队',
					unresize: 'false',
					width: '13%'
				}, {
					field: 'order_num',
					title: '购买人数',
					unresize: 'false',
					width: '13%'
				}]
			];
			break;
	}
}

//公共搜索方法
function formSearch() {
	var data = {};
	data.search_text = $("input[name='search_text']").val();
	data.select_type = $("select[name='select_type']").val();
	data.label_id = $("select[name='label_id']").val();
	data.goods_class = $("select[name='goods_class']").val();
	data.category_id = $("input[name='category_id']").val();
	data.goods_ids = goodsSelect.goodsIdArr.toString();

	table.reload({
		page: {
			curr: 1
		},
		where: data
	});
}

function getGoodsSkuData(goods_id) {
	var list = JSON.parse($("input[name='goods_sku_list_json'][data-goods-id='" + goods_id + "']").val().toString());
	var sku_list = $("#skuList").html();
	var checked = $("input[name='goods_checkbox'][data-goods-id='" + goods_id + "']:checked").length ? true : false;
	return {
		checked: checked,
		sku_list: sku_list,
		list: list
	};
}

//初始化数据
function initData() {
	var goodsLen = $("input[name='goods_checkbox'][data-goods-id]:checked").length;

	//父级
	for (var i = 0; i < goodsLen; i++) {
		var goodsId = $("input[name='goods_checkbox'][data-goods-id]:checked").eq(i).attr("data-goods-id");
		var ident = false;
		for (var k = 0; k < goodsSelect.selectList.length; k++) {
			if (goodsSelect.selectList[k].goods_id == goodsId) {
				ident = true;
				break;
			}
		}

		if (ident) return;

		var json = JSON.parse($("input[name='goods_json'][data-goods-id=" + goodsId + "]").val());
		delete json.LAY_INDEX;
		delete json.LAY_TABLE_INDEX;

		//子级
		var goodsSkuLen = $("input[name='goods_sku_checkbox'][data-goods-id=" + goodsId + "]:checked").length;
		json.selected_sku_list = [];
		for (var j = 0; j < goodsSkuLen; j++) {
			var goodsSkuId = $("input[name='goods_sku_checkbox'][data-goods-id=" + goodsId + "]:checked").eq(j).attr("data-sku-id");
			var skuVal = $("input[name='goods_sku_json'][data-sku-id=" + goodsSkuId + "]").val();
			json.selected_sku_list.push(JSON.parse(skuVal));
		}
		goodsSelect.selectList.push(json);
	}

	// 查询其他页的商品
	var goods_ids = [];
	for (var i = 0; i < goodsSelect.goodsIdArr.length; i++) {
		var is_not = true;
		for (var j = 0; j < goodsSelect.selectList.length; j++) {
			if (goodsSelect.goodsIdArr[i] == goodsSelect.selectList[j].goods_id) {
				is_not = false;
			}
		}
		if (is_not) goods_ids.push([goodsSelect.goodsIdArr[i]]);

	}

	if (goodsSelect.mode == 'spu') {
		if (goods_ids.length > 0) {
			$.ajax({
				url: ns.url("shop/goods/goodsselect"),
				data: {goods_ids: goods_ids.toString(), select_type: 'selected'},
				dataType: 'JSON',
				type: 'POST',
				success: function (res) {
					var list = res.data.list;
					for (var i = 0; i < list.length; i++) goodsSelect.selectList.push(list[i]);
				}
			});
		}
	}

}

//在表格底部增加了一个容器
function dealWithTableSelectedNum() {
	if (goodsSelect.mode == 'spu') {
		$(".layui-table-bottom-left-container").html('已选择 ' + goodsSelect.goodsIdArr.length + ' 个商品');
	} else {
		$(".layui-table-bottom-left-container").html('已选择 ' + goodsSelect.skuIdAll.length + ' 个商品');
	}
}

function selectGoods(callback) {
	var res = goodsSelect.selectList;
	var num = 0;
	if (goodsSelect.mode == "spu") {
		num = goodsSelect.goodsIdArr.length;
		if (goodsSelect.promotion) {
			res = goodsSelect.goodsIdArr;
		}
	} else if (goodsSelect.mode == "sku") {
		num = goodsSelect.skuIdAll.length;
		if (goodsSelect.promotion) {
			res = goodsSelect.skuIdAll;
		}
	}

	if (num == 0) {
		layer.msg('请选择商品');
		return;
	}
	if (goodsSelect.maxNum && goodsSelect.maxNum > 0 && num > goodsSelect.maxNum) {
		layer.msg("所选商品数量不能超过" + goodsSelect.maxNum + '件');
		return;
	}

	if (goodsSelect.minNum && goodsSelect.minNum > 0 && num < goodsSelect.minNum) {
		layer.msg("所选商品数量不能少于" + goodsSelect.minNum + '件');
		return;
	}
	callback(res);
}